package com.example.dp01.service;

import com.example.dp01.constant.REnum;
import com.example.dp01.dao.StudentRepository;
import com.example.dp01.entity.Student;
import com.example.dp01.exception.RException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import java.util.List;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    public List<Student> getAll() {
        return studentRepository.findAll();
    }

    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    public Page<Student>getAll(Example<Student> example,Pageable pageable){
        return studentRepository.findAll(example,pageable);
    }


    public Student add(Student student){
        return studentRepository.save(student);
}
    /**
     * 更新
     */
    public Student update(Student student){
        return studentRepository.save(student);
    }
    /**
     * 删除
     */
    public void  delete(Integer id){
         studentRepository.deleteById(id);
    }
    /**
     * 按ID查询
     * @param id
     * @return
     */
    public Student findById(int id) {
        return studentRepository.findById(id).get();

    }
    /**
     * 按姓名查询
     *
     * @return
     */
    public List<Student> findByName(String name) {
        return studentRepository.findByNameLike(name);

    }
    public void Insert(Student student) {
        studentRepository.save(student);
    }

    public void Update(Student student) {
        studentRepository.save(student);
    }


    public Student findMax(){

        return studentRepository.findAll().stream().max((t1,t2) -> Integer.compare(Integer.parseInt(t1.getSno().substring(0,4)), Integer.parseInt(t2.getSno().substring(0,4)))).orElse(null);
    }


    public Student validateUsernameAndPassword(String sno,String password) throws Exception{
        List<Student> students=studentRepository.findBySno(sno);
        if(students.size()>0){
            Student student=students.get(0);
            if(student.getPassword().equals(password)){
                return student;
            }else{
                throw new RException(REnum.LOGIN_ERR);
            }

        }else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }
}
